package a02;

import java.rmi.RemoteException;

import util.Pair;

public class MinMaxTicTacToeControl extends TicTacToeControl {
    private static final long serialVersionUID = 1L;

    private GameAI<Pair<Byte, Byte>> ai = new MinMaxGame<Pair<Byte, Byte>>();
    private byte[][] lastMoveTable = new byte[this.getBoard().getGame()
                                  	    .getColumns()][this.getBoard().getGame().getRows()];

    public MinMaxTicTacToeControl() {
	this(new TicTacToe(),0);
    }

    public MinMaxTicTacToeControl(TicTacToe g, int kiLevel) {
	super(g,kiLevel,true);
	setGameMode1Player(true);
    }

 

    @Override
    public void whenMousePressed(byte c, byte r) throws RemoteException {
	if (this.getBoard().getGame().currentPlayer() == getPlayerID()) {
	    super.whenMousePressed(c, r);
	    lastMoveTable = convertBoard();
	} else {
	    if (this.getBoard().getGame().ended()) {
		playSound(Sound.FAIL);
		return;
	    }
	    lastMoveTable = convertBoard();
	    this.getBoard().setGame((TicTacToe) this.ai.doBestMove(this.getBoard().getGame()));
	    playSound(Sound.CLICK);
	    getBoard().setLastMove(findLastMove());
	    refresh();
	    handleWin();
	}
    }
    
    private Pair<Byte, Byte> findLastMove() {
   	byte[][] thisMoveTable = convertBoard();
   	Pair<Byte, Byte> lastMove = null;
   	for (byte x = 0; x < this.getBoard().getGame().getColumns(); x++) {
   	    for (byte y = 0; y < this.getBoard().getGame().getRows(); y++) {
   		if(!(lastMoveTable[x][y] == thisMoveTable[x][y]) && thisMoveTable[x][y] == this.getBoard().getGame().otherPlayer( this.getBoard().getGame().currentPlayer())) lastMove = new Pair<Byte,Byte>(x,y);
   	    }
   	}

   	return lastMove;
       }

       private byte[][] convertBoard() {
   	byte[][] convertedList = new byte[this.getBoard().getGame()
   		.getColumns()][this.getBoard().getGame().getRows()];
   	for (byte x = 0; x < this.getBoard().getGame().getColumns(); x++) {
   	    for (byte y = 0; y < this.getBoard().getGame().getRows(); y++) {
   		convertedList[x][y] = this.getBoard().getGame()
   			.getAtPosition(x, y);
   	    }
   	}
   	return convertedList;
       }
}
